<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/4/18 0018
 * Time: 21:48
 */
$sock = socket_create_listen(0);  //在指定端口打开一个socket监听
socket_getsockname($sock, $addr, $port); // 获取本地socket的ip地址
print "Server Listening on $addr:$port\n";
$port_file = 'port.txt';
$fp = fopen($port_file, 'w');
fwrite($fp, $port);
fclose($fp);
while ($client = socket_accept($sock)) {
    /* do something useful */
    socket_getpeername($client, $raddr, $rport); // 获取远程类似主机的ip地址
    print "Received Connection from $raddr:$rport\n";

    $msg = '向客户端发送消息';
    socket_write($client, $msg, strlen($msg));
    //读取客户端消息
    $buf = socket_read($client, 8192);
    echo "收到的信息:$buf\n";
//    socket_close($client);
}
socket_close($sock);